<!-- eslint-disable vue/multi-word-component-names -->
<!-- eslint-disable-next-line vue/valid-template-root -->
<script setup>
import router from '@/router'
import { useI18n } from 'vue-i18n'
// import { emitter } from '@/utils'
import { useNoteTag } from '@/store/noteTag.js'
const target_tag = useNoteTag()
const { t } = useI18n()

defineProps({
  content: { type: String, required: true },
  tags: { type: Array },
  Fn: { type: Object }
})

const SuperContent = (content, tags) => {
  // #tag1 #tag2
  if (tags) {
    tags.sort((a, b) => b.length - a.length)
    tags.forEach((tag) => {
      content = content.replaceAll(
        `#${tag}`,
        `<span class="chip _tag c-hand text-primary" data-name="${tag}">${tag}</span>`
      )
    })
  }

  // /note/{note_id} —> 笔记：{note_id}
  let note_regex = /\/(note)\/[a-zA-Z\d]+\/?/g
  new Set(content.match(note_regex) || []).forEach((quote) => {
    // console.log(quote)
    const id = quote.replace('/note/', '')
    content = content.replaceAll(
      quote,
      `<a href="javascript:void(0);" class="_note text-primary" data-quote="${id}"> 笔记: ${id} </a>`
    )
  })

  // Links https://biji.io
  let url_regex =
    /(https?:\/\/(?:www\.|(?!www))[a-zA-Z\d][a-zA-Z\d-]+[a-zA-Z\d]\.[^\s|^<]{2,}|www\.[a-zA-Z\d][a-zA-Z\d-]+[a-zA-Z\d]\.[^\s|^<]{2,}|https?:\/\/(?:www\.|(?!www))[a-zA-Z\d]+\.[^\s|^<]{2,}|www\.[a-zA-Z\d]+\.[^\s|^<]{2,})/g
  let url_match = content.match(url_regex)
  if (url_match) {
    url_match.forEach((url) => {
      content = content.replaceAll(
        url,
        `<a href="${url}" target="_blank" 
            class="chip _link text-primary tooltip" data-tooltip="${url}"
            style="text-decoration: none;overflow: unset">
          ${t('common.Link')}
        </a>`
      )
    })
  }
  return content
}

const toNoteDetail = (id) => {
  const routeUrl = router.resolve({
    path: `/note/${id}`
  })
  window.open(routeUrl.href, '_blank')
}
const handleClick = (event) => {
  if (event.target.classList.contains('_tag')) {
    const tagName = event.target.getAttribute('data-name')
    target_tag.set(tagName)
  }
  if (event.target.classList.contains('_note')) {
    const noteId = event.target.getAttribute('data-quote')
    toNoteDetail(noteId)
  }
}
</script>
<template>
  <div class="article-content" @click="handleClick" v-html="SuperContent(content, tags)"></div>
</template>

<style lang="scss">
.article-content {
  *:not(:last-child) {
    margin-bottom: 0.2rem;
  }
  :last-child {
    margin-bottom: 0;
  }

  ol,
  ul {
    li {
      p {
        display: inline;
      }
    }
  }
}
</style>
